package com.ma4567.remotecontroller.FileRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ma4567.remotecontroller.MysqlHelper.TableLogManager;
import com.ma4567.remotecontroller.MysqlHelper.TableRequestLog;
import com.ma4567.remotecontroller.RemoteControllerApplication;
import com.ma4567.remotecontroller.ffmpegManager.ffmpegController;
import com.ma4567.remotecontroller.util.File;
import com.ma4567.remotecontroller.util.LocalFileScanner;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.ArrayList;

class FileListRespone{
    public ArrayList<File> FileList;
    public int Status;//0 正常 1 cookie错误 2 所给路径非文件夹

    public FileListRespone(int Status, ArrayList<File> FileList){
        this.FileList = FileList;
        this.Status = Status;
    }

    public FileListRespone(int Status){
        this.Status = Status;
        this.FileList = null;
    }
}

@CrossOrigin
@RestController
public class FileListRequest {
    @RequestMapping(value = "/api/getDirectoryIndex", method = RequestMethod.GET)
    public String getDirectoryIndex(HttpServletRequest request,
                                    @RequestParam("cookie") String Cookie,
                                    @RequestParam("path") String path) throws SQLException {
        ffmpegController.StopStream();

        TableRequestLog.AddLog("Get file list at: " + path, Cookie, request.getRemoteAddr());

        if(!RemoteControllerApplication.userManager.JudgeCookie(Cookie)){//鉴权
            return JSONObject.toJSONString(new FileListRespone(1), SerializerFeature.PrettyFormat);
        }
        else {
            if(!(new java.io.File(path).isDirectory()) && !"Root".equals(path)){
                return JSONObject.toJSONString(new FileListRespone(2), SerializerFeature.PrettyFormat);
            }
            else{
                RemoteControllerApplication.userManager.SetLoggedUserCurrentPath(Cookie, path);
                TableLogManager.AddLog("Get file list at: " + path, Cookie);
                return JSONObject.toJSONString(new FileListRespone(0, LocalFileScanner.GetDictoryFile(path)), SerializerFeature.PrettyFormat);
            }
        }
    }
}
